import { DirectiveBinding } from 'vue'

const autoScrollDirective = {
  /**
   * 当指令绑定到元素上时调用
   * @param {HTMLElement} el - 指令绑定的元素
   * @param {DirectiveBinding} binding - 指令的绑定对象
   */
  mounted (el: HTMLElement, binding: DirectiveBinding) {
    const content = el.querySelector('span')
    if (!content) return

    /**
     * 更新滚动状态
     */
    const updateScroll = () => {
      const contentWidth = content.scrollWidth
      const containerWidth = el.clientWidth
      if (contentWidth > containerWidth) {
        content.classList.add('animate-scroll')
      } else {
        content.classList.remove('animate-scroll')
      }
    }

    updateScroll()
    window.addEventListener('resize', updateScroll)
  },
  /**
   * 当指令与元素解绑时调用
   */
  unmounted () {
    window.removeEventListener('resize', () => { })
  }
}

export default autoScrollDirective
